import { memo, useState, useCallback } from 'react'
import { Avatar, Divider, Layout, theme, ConfigProvider, Flex, Popover, Button, Tooltip, Dropdown, Space, Typography, Input, message, Modal } from 'antd';
const { Title } = Typography;
import { DownOutlined, UserOutlined, AntDesignOutlined, TeamOutlined } from '@ant-design/icons';
import React from 'react';
import { getDocShareCode, verifyDocShareCode, saveDocMessage } from '../../api';
import { useNavigate } from 'react-router-dom';
import styles from './index.module.less';
import { useMemo } from 'react';
import { throttle } from '@/utils/debounceThrottle';

const { Header } = Layout;
const DocDetailHead = ({
    docId, docName, setDocName, docPermission, setDocPermission,
    docContent, setDocContent, isJoinedViaShareCode = false
}) => {
    // 加入协作相关状态
    const [joinCode, setJoinCode] = useState('');
    const [joinLoading, setJoinLoading] = useState(false);
    const [joinModalOpen, setJoinModalOpen] = useState(false);

    const hasSelectedDoc = !!docId && docId !== 'new';

    // 文档名称状态
    const [isEditing, setIsEditing] = useState(false);

    // 分享模态框状态
    const [shareModalOpen, setShareModalOpen] = useState(false);
    // 分享权限
    const [sharePermission, setSharePermission] = useState('仅阅读');

    const navigate = useNavigate();
    // 处理加入协作 - 使用 useCallback 稳定函数引用
    const handleJoinCollaboration = useCallback(async () => {
        if (!joinCode.trim()) {
            message.error('请输入分享码！');
            return;
        }

        setJoinLoading(true);
        try {
            // 调用后端校验接口
            const res = await verifyDocShareCode(joinCode.trim());
            if (res && res.code === 200 && res.data) {
                message.success('成功加入协作！');
                setJoinCode('');
                setJoinModalOpen(false);
                // 显示“成功加入协作！” 提示后，1s后刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 1000);

                // 跳转到详情页，并传递文档详情
                navigate(`/docList/docDetail/${res.data.docId}`, {
                    state: {
                        docName: res.data.docName,
                        docContent: typeof res.data.docContent === 'string'
                            ? JSON.parse(res.data.docContent)
                            : res.data.docContent,
                        docPermission: res.data.docPermission,
                        isJoinedViaShareCode: true
                    }
                });
            } else {
                message.error(res?.msg || '加入协作失败');
            }
        } catch (err) {
            message.error('加入协作失败，请检查分享码是否正确');
        } finally {
            setJoinLoading(false);
        }
    }, [joinCode, navigate]);

    // 处理文档名称编辑
    const handleDocNameChange = (e) => {
        setDocName(e.target.value);
    };

    const handleDocNameBlur = () => {
        setIsEditing(false);
        // 这里可以调用API保存文档名称
        // await updateDocName({ name: docName });
    };

    const handleDocNamePressEnter = () => {
        setIsEditing(false);
        // 这里可以调用API保存文档名称
        // await updateDocName({ name: docName });
    };

    // 头像
    const UserAvatar = () => (
        <div className={styles.avatarWrap}>
            <Avatar.Group
                size="large"
                max={{
                    count: 2,
                    style: { color: '#f56a00', backgroundColor: '#fde3cf' },
                }}
            >
                <Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=3" />
                <Avatar style={{ backgroundColor: '#f56a00' }}>K</Avatar>
                <Tooltip title="Ant User" placement="top">
                    <Avatar style={{ backgroundColor: '#87d068' }} icon={<UserOutlined />} />
                </Tooltip>
                <Avatar style={{ backgroundColor: '#1677ff' }} icon={<AntDesignOutlined />} />
            </Avatar.Group>
            <Divider />
        </div>
    );
    // 权限
    const PermissionsBtn = () => {
        const handleMenuClick = e => setDocPermission(e.key);
        const items = [
            { label: '仅阅读', key: '仅阅读' },
            { label: '可编辑', key: '可编辑' },
            { label: '可修订', key: '可修订' },
        ];
        const menuProps = { items, onClick: handleMenuClick };
        return (
            <Space wrap className={styles.permissionsBtn}>
                <Dropdown menu={menuProps} disabled={isJoinedViaShareCode}>
                    <Button disabled={isJoinedViaShareCode}>
                        <Space>
                            {docPermission}
                            {!isJoinedViaShareCode && <DownOutlined />}
                        </Space>
                    </Button>
                </Dropdown>
            </Space>
        );
    };

    // 需要能拿到 docId 和 docPermission
    // 你可以通过 props 传递 docId
    const handleCopyShareCode = async () => {
        if (!docName || !sharePermission) {
            message.error('请先选择分享权限');
            return;
        }
        const res = await getDocShareCode(docId, sharePermission);
        try {
            if (res && res.code === 200 && res.data) {
                await navigator.clipboard.writeText(res.data);
                message.success('分享码已复制到剪贴板');
                // 显示“分享码已复制到剪贴板” 提示后，1s后刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                message.error('获取分享码失败');
            }
        } catch (err) {
            message.error('获取分享码失败');
        }
    };

    // 分享
    const ShareBtn = () => {
        const content = (
            <div style={{ margin: 5 }}>
                <PermissionsBtn />
                <Flex gap="small" wrap>
                    <Button
                        type="primary"
                        style={{ width: '80%' }}
                        onClick={handleCopyShareCode}
                    >
                        复制分享码
                    </Button>
                </Flex>
            </div>
        );
        const buttonWidth = 80;
        const ShareBtn = () => {
            return (
                <Button onClick={() => setShareModalOpen(true)}>
                    分享
                </Button>
            );
        };
        return (
            <Button onClick={() => setShareModalOpen(true)}
                disabled={!hasSelectedDoc || docPermission === '仅阅读'}>
                分享
            </Button>
        );
    }

    // 加入协作
    const JoinCollaborationBtn = () => {
        const buttonWidth = 80;
        return (
            <ConfigProvider button={{ style: { width: buttonWidth, margin: 4 } }}>
                <Flex vertical justify="center" align="center" className="demo">
                    <Flex justify="center" align="center" style={{ whiteSpace: 'nowrap' }}>
                        <Button
                            icon={<TeamOutlined />}
                            onClick={() => setJoinModalOpen(true)}
                        >
                            加入协作
                        </Button>
                    </Flex>
                </Flex>
            </ConfigProvider>
        )
    }

    // 版本管理
    const VersionManagement = () => (
        <div className={styles.versionManagement}>
            <Button disabled={!hasSelectedDoc || docPermission === '仅阅读'}>
                <Space>
                    版本管理
                </Space>
            </Button>
        </div>
    )

    // 保存    
    const handleSave = async () => {
        // 这里假设 docId, docName, docContent, docPermission, knowledgeBaseId, isBelongToKnowledgeBase 都在 props 或 state
        if (!docName || !docContent) {
            message.error('文档名称和内容不能为空');
            return;
        }
        const userId = localStorage.getItem('userId');
        const data = {
            docId: docId === 'new' ? undefined : docId, // 新建时不传docId
            docName,
            userId,
            docPermission, 
            docContent: JSON.stringify(docContent),
            // 下面两个字段按需传递
            isBelongToKnowledgeBase: '0',
            knowledgeBaseId: ''
        };
        try {
            const res = await saveDocMessage(data);
        if (res && res.code === 200) {
            message.success('保存成功');
            // 新建文档时，跳转到新文档详情页
            if (docId === 'new' && res.data) {
                navigate(`/docList/docDetail/${res.data}`);
            }
        } else {
            message.error(res?.msg || '保存失败');
        }
    } catch (err) {
        message.error('保存失败');
    }
};
    const SaveBtn = () => (
        <Button onClick={throttledSave} disabled={docPermission === '仅阅读'}>
            <Space>
                保存
            </Space>
        </Button>
    );
    
    const throttledSave = useMemo(() => throttle(handleSave, 500), [handleSave]);
    const throttledCopy = useMemo(() => throttle(handleCopyShareCode, 500), [handleCopyShareCode]);
    const throttledJoin = useMemo(() => throttle(handleJoinCollaboration, 500), [handleJoinCollaboration]);


    return (
        <div className={styles.docDetailHead}>
            <Header className={styles.header}>
                <div className={styles.docNameContainer}>
                    <span className={styles.docNameLabel}>文档名称：</span>
                    {isEditing ? (
                        <Input
                            disabled={docPermission === '仅阅读'}
                            value={docName}
                            onChange={handleDocNameChange}
                            onBlur={handleDocNameBlur}
                            onPressEnter={handleDocNamePressEnter}
                            className={styles.docNameInput}
                            autoFocus
                        />
                    ) : (
                        <Title
                            level={4}
                            className={styles.docNameTitle}
                            onClick={() => setIsEditing(true)}
                        >
                            {docName}
                        </Title>
                    )}
                </div>
                <div className={styles.rightWrap}>
                    <UserAvatar />
                    <PermissionsBtn />
                    <JoinCollaborationBtn />
                    <ShareBtn />
                    {/* <VersionManagement /> */}
                    <SaveBtn />
                </div>
            </Header>

            {/* 分享Modal */}
            <Modal
                title="分享文档"
                open={shareModalOpen}
                onCancel={() => setShareModalOpen(false)}
                footer={null}
                width={400}
                centered
            >
                <div className={styles.shareModalContent}>
                    {/* 权限选择 */}
                    <div className={styles.permissionSelect}>
                        <span className={styles.permissionLabel}>权限：</span>
                        <Dropdown
                            menu={{
                                items: [
                                    { label: '仅阅读', key: '仅阅读' },
                                    { label: '可编辑', key: '可编辑' },
                                    // { label: '可修订', key: '可修订' },
                                ],
                                onClick: (e) => setSharePermission(e.key),
                            }}
                        >
                            <Button>
                                {sharePermission} <DownOutlined />
                            </Button>
                        </Dropdown>
                    </div>
                    <Button
                        type="primary"
                        className={styles.copyShareCodeBtn}
                        onClick={throttledCopy}
                    >
                        复制分享码
                    </Button>
                </div>
            </Modal>

            {/* 加入协作的 Modal */}
            <Modal
                title="加入协作"
                open={joinModalOpen}
                onCancel={() => setJoinModalOpen(false)}
                footer={null}
                width={400}
                centered
            >
                <div className={styles.joinModalContent}>
                    <div style={{ marginBottom: '12px' }}>
                        <label className={styles.shareCodeLabel}>
                            分享码：
                        </label>
                        <Input
                            placeholder="请输入分享码"
                            value={joinCode}
                            onChange={(e) => setJoinCode(e.target.value)}
                            onPressEnter={throttledJoin}
                            className={styles.shareCodeInput}
                            autoFocus
                        />
                    </div>
                    <Flex gap="small" wrap>
                        <Button
                            type="primary"
                            className={styles.joinBtn}
                            onClick={throttledJoin}
                            loading={joinLoading}
                        >
                            确定加入
                        </Button>
                    </Flex>
                </div>
            </Modal>
        </div>
    );
}

export const MemoDocDetailHead = memo(DocDetailHead)